package com.jqb.jspcart.service.impl;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;

import com.jqb.jspcart.bean.Hardware;

public class CartServiceImpl {
	private HashMap<Integer,Hardware> cart = new HashMap<Integer,Hardware>();
	
	//增加(最多添加50样)
	public boolean addGoods(int id,int num){
		boolean flag = false;
		int size = this.getSizeOfCart();
		Hardware hardware = null;
		if (cart.containsKey(id)) {
			hardware = cart.get(id);
			int newnum = num + hardware.getNum();
			hardware.setNum(newnum);
			flag=true;
		} else if(size<50){
			try {
				hardware = HardwareServiceImpl.newInstance().getHardware(id);
			} catch (SQLException e) {
				e.printStackTrace();
			}
			hardware.setNum(num);
			cart.put(id, hardware);
			flag=true;
		}
		return flag;
	}
	
	//删除
	public boolean delGoods(int id){
		boolean flag = false;
		if(cart.containsKey(id)){
			cart.remove(id);
		}
		return flag;
	}
	
	//更新
	public boolean updateGoods(int id,int num){
		boolean flag = false;
		Hardware hardware = null;
		if(cart.containsKey(id)){
			hardware = cart.get(id);
			hardware.setNum(num);
		}
		return flag;
	}
	
	//查看
	public ArrayList<Hardware> getGoods(){
		ArrayList<Hardware> goods = new ArrayList<Hardware>();
		Hardware hardware = null;
		Iterator<Integer> it = cart.keySet().iterator();
		while(it.hasNext()){
			hardware = cart.get(it.next());
			goods.add(hardware);
		}
		return goods;
	}
	
	//查看当前购物车的size
	public int getSizeOfCart(){
		int size = 0;
		size = cart.size();
		return size;
	}
	
	//获得总价
	public float getSum(){
		float sum = 0.0f;
		Iterator<Integer> it = cart.keySet().iterator();
		Hardware hardware = null;
		while(it.hasNext()){
			hardware = cart.get(it.next());
			float p = hardware.getPrice();
			float n = hardware.getNum();
			sum = sum + p*n;
		}
		return sum;
	}
	
	public static CartServiceImpl newInstance(){
		return new CartServiceImpl();
	}
}
